package com.cq.base.bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothSocket
import kotlinx.coroutines.runBlocking
import java.io.OutputStream
import java.util.*

/**
 * 作者: CQ
 * 日期: 2021-11-11
 * 说明:
 */
class BlueToothService {
    companion object {
        @Volatile
        private var blueToothService : BlueToothService? = null

        @Synchronized
        fun getInstance() : BlueToothService {
            if (blueToothService == null) {
                blueToothService = BlueToothService()
            }
            return blueToothService!!
        }

        // 通用uuid
        val uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")!!
    }

    // 本地蓝牙适配器
    private val bluetoothAdapter by lazy { BluetoothAdapter.getDefaultAdapter() }

    // 远程蓝牙设备
    private lateinit var device : BluetoothDevice

    // 蓝牙socket，交换数据
    private lateinit var bluetoothSocket : BluetoothSocket

    // 蓝牙是否已连接
    private var isConnection = false
    private lateinit var outputStream : OutputStream

    /**
     * 第一步：判断蓝牙是否开启
     * 第二步：获取绑定的蓝牙设备
     * 第三步：获取蓝牙设备地址
     * 第四步：建立连接
     */
    fun onStartPrint() : Boolean = runBlocking {
        if (isOpen()) {
            //  获取与本机蓝牙所有绑定的远程蓝牙信息
            val bondedDevices = bluetoothAdapter.bondedDevices
            if (bondedDevices.size > 0) {
                // 取第一个设备的地址
                device = bluetoothAdapter.getRemoteDevice(bondedDevices.toTypedArray()[0].address)
            }
            onConnect()
        }
        return@runBlocking false
    }

    /**
     * 连接蓝牙设备
     */
    private fun onConnect() : Boolean {
        if (isConnection) {
            return true
        }
        try {
            //获取蓝牙socket对象
            bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid)
            bluetoothSocket.connect()
            outputStream = bluetoothSocket.outputStream
            isConnection = true
            // 是否正在处于扫描过程中
//            if (bluetoothAdapter.isDiscovering) {
//
//            }
        } catch (e : Exception) {
            e.printStackTrace()
            return false
        }
        return true
    }




    // 蓝牙是否打开
    private fun isOpen() = bluetoothAdapter.isEnabled

}